package com.xcc.mrpbmp;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by 磁磁帅 on 2021/6/5.
 * 功能：
 */
public class JpgActivity extends AppCompatActivity {
    public static final String[] AssetsJpgData = new String[]{
            "meimei.jpg",
            "1.jpg"};
    @BindView(R.id.image)
    ImageView imageView;
    @BindView(R.id.textView)
    TextView textView;
    private int index;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @OnClick(R.id.image)
    public void onImageClicked() {
        loadBitmap(index);
        index++;
        if (index >= AssetsJpgData.length) index = 0;
    }

    private void loadBitmap(int index) {
        final String assetsName = AssetsJpgData[index];
        new Thread() {
            @Override
            public void run() {
                long timeMillis = System.currentTimeMillis();
                final Bitmap bitmap = loadBitmap(assetsName);
                final long l = System.currentTimeMillis() - timeMillis;
                if (bitmap == null) return;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        imageView.setImageBitmap(bitmap);
                        textView.setText(l + "毫秒");
                    }
                });
            }
        }.start();
    }

    public Bitmap loadBitmap(String assetsName) {
        InputStream resourceAsStream = this.getClass().getClassLoader()
                .getResourceAsStream("assets/" + assetsName);
        Bitmap bitmap = BitmapFactory.decodeStream(resourceAsStream);
        try {
            resourceAsStream.close();
        } catch (IOException e) {
            if (BuildConfig.DEBUG) e.printStackTrace();
        }
        return bitmap;
    }
}
